
#include "RequestGet.h"
#include "BasicModule.h"
#include "../client-common/Config.h"
#include "../port/System.h"

using namespace Client::Common;

map<string, CRequestAction*> CRequestGet::mActions;

void CRequestGet::DoRequest() {
		
	string& target = GetParameter(string("target"));
	Engine::DebugStream << "CRequestGet - target : " << target << '\n';

	if(target.length() == 0) {
		Response(RESPONSE_STATUS_BadRequest);
		return;
	}

	map<string, CRequestAction*>::iterator i = mActions.find(target);
	if(i != mActions.end()) {
		ResponseRef response = InitResponse();
		i->second->DoRequest(*this, *response);
		mConnection->SendResponse(response);
	}
	else {
		Response(RESPONSE_STATUS_BadRequest);
	}
	/*
	if(target == "filelist") {
	GetFileList();
	}
	else 
	if(target == "file") {
	GetFile();
	}
	else
	if(target == "devices") {
	GetDevices();
	}
	else {
	Response(RESPONSE_STATUS_BadRequest);
	}
	*/
}

class CActionGetDevices : public CRequestAction {

public :

	virtual void DoRequest(CRequest& request, CResponse& response) {

		TableRef td = Client::Common::CDevice::Query();
		if(!td) td = Client::Common::CDevice::GetSerializedTable();

		DeviceRef me(new Client::Common::CDevice());
		me->mId = CConfig::GetInstance().mDeviceId;
		me->mName = Util::CSystem::GetHostName();
		td->Add(me);

		TableRef ts = Client::Common::CDevice::GetSerializedTable(*td);
		td->Close();

		string js = ts->ToString();
		ts->Close();
		
		response.SetStatus(RESPONSE_STATUS_OK);
		response.SetContent(js, string(PACKAGE_CONTENT_TYPE_JSON));
	}

};

static CActionGetDevices sActionGetDevices;

void CBasicModule::InitGetAction()
{
	CRequestGet::RegisterAction(string("devices"), &sActionGetDevices);
}
